﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using SmartMeterParamFrame.Model;
using SmartMeterParamFrame;
using System.ServiceModel;
using System.Data;
using Comm.Util;
using Comm.HardDisk;

namespace SchemeManager
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 方案管理器
        /// </summary>
        private SchemeHelper schemeManager = null;

        public MainWindow()
        {
            InitializeComponent();
            HideMask();
            Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        /// <summary>
        /// 窗口加载完毕事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            DataGridComboBoxColumn col = this.Grid_Group.Columns[this.Grid_Group.Columns.Count - 1] as DataGridComboBoxColumn;
            col.ItemsSource = Enum.GetValues(typeof(EnumCheckType));
            //加载方案数据
            InitailizeSchemes();
            DataContext = schemeManager.Schemes;
        }

        /// <summary>
        /// 加载已经存在的方案
        /// </summary>
        private void InitailizeSchemes()
        {
            schemeManager = new SchemeHelper();
            if (!schemeManager.LoadAllSchemes())
            {
                MessageBox.Show("加载方案列表失败");
            }
        }

        /// <summary>
        /// 基本参数删除事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button btnSource = sender as Button;
            if (btnSource == null) return;
            FACollection currentScheme = null;

            if (Lst_PrjItems.SelectedItem == null) return;
            currentScheme = Lst_PrjItems.SelectedItem as FACollection;

            if (currentScheme == null) return;
            if (btnSource.Name == "btnImport")
            {
                System.Windows.Forms.OpenFileDialog openFile = new System.Windows.Forms.OpenFileDialog();
                System.Windows.Forms.DialogResult ret = openFile.ShowDialog();
                if (ret != System.Windows.Forms.DialogResult.OK)
                    return;
                string templatePath = openFile.FileName;

                string strconn = "";

                //office 2007 版本，或者office 2010 版本
                //office 2007版本驱动 http://www.microsoft.com/en-us/download/details.aspx?id=23734
                //office 2010版本驱动 http://www.microsoft.com/en-us/download/details.aspx?id=13255
                if (templatePath.EndsWith(".xlsx"))
                {
                    strconn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + templatePath + ";Extended Properties=\"Excel 12.0 Xml" + ";HDR=Yes;IMEX=1;\"";
                }
                else
                {
                    strconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + templatePath + ";Extended Properties=\"Excel 8.0" + ";HDR=Yes;IMEX=1;\"";
                }
                System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(strconn);
                conn.Open();
                DataTable dt = conn.GetSchema();
                DataRow dr = dt.Rows[0];
                System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("Select * from [Sheet1$]");
                cmd.Connection = conn;
                System.Data.IDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        FAinfo newItem = new FAinfo();
                        newItem.PrjName = reader[1].ToString();
                        EnumFAType faType = EnumFAType.其他操作;
                        Enum.TryParse<EnumFAType>(reader[0].ToString(), out faType);
                        newItem.PrjType = faType;
                        newItem.BsCode = reader[2].ToString();
                        newItem.DataDomainDP = reader[3].ToString();
                        try
                        {
                            newItem.ReviewType = (EnumCheckType)(Enum.Parse(typeof(EnumCheckType), reader[4].ToString()));
                        }
                        catch
                        {
                            newItem.ReviewType = EnumCheckType.仅复核;
                        }
                        currentScheme.Add(newItem);
                    }
                    reader.Close();
                }
                conn.Close();
            }
            else if (btnSource.Name == "btnAddItems")
            {
                //批量加入
                SelectItem selectBox = new SelectItem();
                bool? ret = selectBox.ShowDialog();
                if (ret == null) return;
                if (ret == true)
                {
                    if (selectBox.SelectedItems == null) return;

                    foreach (SmartMeterParamFrame.Model.FAinfo item in selectBox.SelectedItems)
                    {
                        currentScheme.Add(item);
                    }
                }
            }
            else
            {

                //检测选择的项目
                object currentItem = Grid_Group.SelectedItem;
                if (currentItem == null) return;
                FAinfo currentFA = currentItem as FAinfo;
                if (currentFA == null) return;
                if (btnSource.Name == "btnUp" || btnSource.Name == "btnDown")
                {
                    bool isUp = btnSource.Name == "btnUp";
                    //上移
                    int sourcePos = currentScheme.IndexOf(currentFA);
                    if (isUp)
                    {
                        if (currentScheme.MoveFainfo(currentFA, -1) == true)
                        {
                            Grid_Group.SelectedItem = currentScheme[sourcePos - 1];
                        }
                    }
                    //下移
                    else
                    {
                        if (currentScheme.MoveFainfo(currentFA, 1) == true)
                        {
                            Grid_Group.SelectedItem = currentScheme[sourcePos + 1];
                        }
                    }
                }
                else
                {
                    if (MessageBox.Show("确定要删除项目[" + currentFA.PrjName + "]吗？", "系统提示", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    {
                        return;
                    }
                    currentScheme.Remove(currentFA);
                }
            }
        }

        private void Lst_PrjItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Lst_PrjItems.SelectedItem == null) return;
            FACollection currentScheme = Lst_PrjItems.SelectedItem as FACollection;
            if (currentScheme == null) return;
            ListCollectionView col = new ListCollectionView(currentScheme);
            col.GroupDescriptions.Add(new PropertyGroupDescription("PrjType"));
            Grid_Group.ItemsSource = col;
            this.cbFaReview.IsChecked = currentScheme.OperationType == EnumCheckType.仅复核;
        }

        /// <summary>
        /// 工具条事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolBarButton_Click(object sender, RoutedEventArgs e)
        {
            Button sourceButton = sender as Button;
            if (sourceButton == null) return;
            switch (sourceButton.Name)
            {
                case "Btn_Config":
                    {
                        SystemConfig config = new SystemConfig();
                        config.ShowDialog();
                    }
                    break;
                case "Btn_NewScheme":
                    {
                        //新建方案
                        SchemeNameInput inputbox = new SchemeNameInput();
                        inputbox.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                        bool ret = (bool)inputbox.ShowDialog();
                        if (ret == false) return;
                        foreach (FACollection scheme in schemeManager.Schemes)
                        {
                            if (scheme.FAName == inputbox.SchemeName)
                            {
                                MessageBox.Show(string.Format("系统中已经存在名称为[{0}]的方案，请重新输入一个方案", inputbox.SchemeName));
                                return;
                            }
                        }
                        FACollection newScheme = new FACollection();
                        newScheme.FAName = inputbox.SchemeName;
                        newScheme.OperationType = inputbox.SchemeOperationType;
                        schemeManager.Schemes.Add(newScheme);
                        inputbox.Close();
                    }
                    break;
                case "Btn_SaveScheme":
                    {
                        //保存方案
                        if (Lst_PrjItems.SelectedItem == null) return;
                        FACollection currentScheme = Lst_PrjItems.SelectedItem as FACollection;
                        if (currentScheme == null) return;
                        currentScheme.OperationType = this.cbFaReview.IsChecked.Value ? EnumCheckType.仅复核 : EnumCheckType.复核修正复核;
                        //排序
                        int pos = 1;
                        foreach (FAinfo item in currentScheme)
                        {
                            item.PrjOrderID = pos++;
                        }
                        if (schemeManager.SaveScheme(currentScheme))
                            MessageBox.Show(string.Format("保存方案[{0}]成功", currentScheme.FAName));
                        else
                            MessageBox.Show("保存方案失败");
                    }
                    break;
                case "Btn_DeleteScheme":
                    {
                        //删除方案
                        if (Lst_PrjItems.SelectedItem == null) return;
                        FACollection currentScheme = Lst_PrjItems.SelectedItem as FACollection;
                        if (currentScheme == null) return;
                        if (MessageBox.Show(string.Format("确定要删除方案[{0}]吗？", currentScheme.FAName), "系统提示", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                        {
                            if (schemeManager.DeleteScheme(currentScheme) == false)
                            {
                                MessageBox.Show("删除方案:" + currentScheme.FAName + "失败");
                            }
                            else
                            {
                                this.Grid_Group.ItemsSource = null;
                            }
                        }
                    }
                    break;
                case "Btn_Close":
                    {
                        this.Close();
                    }
                    break;
            }
        }

        /// <summary>
        /// 显示遮罩层
        /// </summary>
        /// <param name="message"></param>
        private void ShowMask(string message)
        {
            System.Threading.Tasks.Task t = new System.Threading.Tasks.Task((new Action(() =>

                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    ////txtMessage.Text = message;
                    //while (Grid_Mask.Height < Height)
                    //{
                    //    Grid_Mask.Height += 2;
                    //    SmartMeterParamFrame.ApplocationDoEvents.DoEvents();
                    //}
                }))
            )));
            t.Start();
        }

        /// <summary>
        /// 隐藏遮罩层
        /// </summary>
        private void HideMask()
        {
            //Grid_Mask.Height = 0;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //退出系统
            if (MessageBox.Show("确定要退出当前系统吗 ？", "系统提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                App.Current.Shutdown();
                //System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void btnGroupUp_Click(object sender, RoutedEventArgs e)
        {
            this.MoveGroup(-1);
        }

        private void btnGroupDown_Click(object sender, RoutedEventArgs e)
        {
            this.MoveGroup(1);
        }

        private void MoveGroup(int forward)
        {
            FAinfo currentFA = Grid_Group.SelectedItem as FAinfo;
            FACollection currentScheme = Lst_PrjItems.SelectedItem as FACollection;

            if (currentFA == null || currentScheme == null)
                return;
            currentScheme.MoveGroup(currentFA, forward);
        }
    }
}
